package com.janal.controller.Login_Register;

import com.janal.model.user.User;
import com.janal.service.login.LoginServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取用户输入的账号密码
        String usercode = req.getParameter("usercode");
        String password = req.getParameter("password");
        User getuser = new User(usercode, password);

        //调用service进行用户匹配
        LoginServiceImpl lsi = new LoginServiceImpl();
        User resultuser = lsi.login(getuser);

        if (resultuser == null) {
            req.setAttribute("error", "该用户不存在，请先注册！");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        } else if (resultuser.getPassword() == null) {
            req.setAttribute("error", "密码错误！");
            req.getRequestDispatcher("login.jsp").forward(req, resp);
        } else {      //登录成功
            //将账号密码存储到Session中
            HttpSession session = req.getSession();
            session.setAttribute("usercode",usercode);
            session.setAttribute("password",password);
            session.setAttribute("usersession", resultuser);
            resp.sendRedirect("/p/Home_page.html");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}